package com.rongzhe.house.common.utils;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by hggxg on 2017/11/15.
 */
public class OkHttpUtil {


    private static final OkHttpClient mOkHttpClient = new OkHttpClient.Builder().connectTimeout(10L, TimeUnit.SECONDS).writeTimeout(10L, TimeUnit.SECONDS).readTimeout(30L, TimeUnit.SECONDS).build();

    public static Response execute(Request request)
            throws IOException
    {
        return mOkHttpClient.newCall(request).execute();
    }

    public static void enqueue(Request request, Callback responseCallback)
    {
        mOkHttpClient.newCall(request).enqueue(responseCallback);
    }

    public static void enqueue(Request request)
    {
        mOkHttpClient.newCall(request).enqueue(new Callback()
        {
            public void onFailure(Call call, IOException e) {}

            public void onResponse(Call call, Response response)
                    throws IOException
            {}
        });
    }

    public static String getStringFromServer(String url)
            throws IOException
    {
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request);
        if (response.isSuccessful())
        {
            String responseUrl = response.body().string();
            return responseUrl;
        }
        throw new IOException("Unexpected code " + response);
    }

}
